#!/bin/bash

# Web3项目管理工具Docker一键部署脚本
# 版本: 2.0.0 Docker Edition

set -e

echo "============================================="
echo "    Web3项目管理工具Docker部署脚本 v2.0.0"
echo "============================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印彩色日志
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help          显示帮助信息"
    echo "  --dev               开发模式部署（暴露数据库和Redis端口）"
    echo "  --prod              生产模式部署（仅暴露前端端口）"
    echo "  --rebuild           强制重新构建镜像"
    echo "  --no-cache          构建时不使用缓存"
    echo "  --stop              停止所有服务"
    echo "  --restart           重启所有服务"
    echo "  --logs              查看服务日志"
    echo "  --status            查看服务状态"
    echo ""
    echo "示例:"
    echo "  $0                  # 默认部署"
    echo "  $0 --dev            # 开发模式部署"
    echo "  $0 --prod           # 生产模式部署"
    echo "  $0 --rebuild        # 重新构建并部署"
    echo "  $0 --stop           # 停止服务"
    echo "  $0 --logs           # 查看日志"
}

# 检查Docker环境
check_docker() {
    log_step "检查Docker环境..."

    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        echo "安装命令（Ubuntu/Debian）:"
        echo "  curl -fsSL https://get.docker.com -o get-docker.sh"
        echo "  sudo sh get-docker.sh"
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        log_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi

    # 检查Docker服务状态
    if ! docker info &> /dev/null; then
        log_error "Docker服务未启动，请启动Docker服务"
        exit 1
    fi

    log_info "Docker环境检查完成"
}

# 检查项目文件
check_project_files() {
    log_step "检查项目文件..."

    required_files=(
        "docker-compose.yml"
        "backend/Dockerfile"
        "frontend/Dockerfile"
        "init.sql"
    )

    for file in "${required_files[@]}"; do
        if [ ! -f "$file" ]; then
            log_error "缺少必要文件: $file"
            exit 1
        fi
    done

    log_info "项目文件检查完成"
}

# 准备环境配置
prepare_environment() {
    log_step "准备环境配置..."

    # 检查.env文件是否存在
    if [ ! -f ".env" ]; then
        log_warn ".env文件不存在，从示例文件创建..."
        if [ -f ".env.example" ]; then
            cp .env.example .env
            log_info "已创建.env文件，请根据需要修改配置"
        else
            log_warn "未找到.env.example文件，使用默认配置"
        fi
    fi

    # 创建必要的目录
    mkdir -p logs
    mkdir -p nginx/conf.d
    mkdir -p nginx/ssl
    mkdir -p config

    log_info "环境准备完成"
}

# 构建镜像
build_images() {
    log_step "构建Docker镜像..."

    local rebuild_flag=""
    local cache_flag=""

    if [[ "$REBUILD" == "true" ]]; then
        rebuild_flag="--force-recreate"
    fi

    if [[ "$NO_CACHE" == "true" ]]; then
        cache_flag="--no-cache"
    fi

    # 构建镜像
    if command -v docker-compose &> /dev/null; then
        docker-compose build $cache_flag
    else
        docker compose build $cache_flag
    fi

    log_info "镜像构建完成"
}

# 启动服务
start_services() {
    log_step "启动Docker服务..."

    local compose_file="docker-compose.yml"
    local additional_args=""

    # 根据模式选择配置
    if [[ "$MODE" == "dev" ]]; then
        log_info "使用开发模式启动..."
        # 开发模式可以添加额外的端口映射
        additional_args="-f docker-compose.dev.yml"
    elif [[ "$MODE" == "prod" ]]; then
        log_info "使用生产模式启动..."
        additional_args="-f docker-compose.prod.yml"
    fi

    # 启动服务
    if command -v docker-compose &> /dev/null; then
        docker-compose $additional_args up -d $rebuild_flag
    else
        docker compose $additional_args up -d $rebuild_flag
    fi

    log_info "Docker服务启动完成"
}

# 等待服务就绪
wait_for_services() {
    log_step "等待服务启动..."

    # 等待MySQL
    log_info "等待MySQL服务..."
    local mysql_ready=false
    for i in {1..30}; do
        if docker exec web3-mysql mysqladmin ping -h localhost -u root -p123456 &> /dev/null; then
            mysql_ready=true
            break
        fi
        echo -n "."
        sleep 2
    done

    if [[ "$mysql_ready" == "false" ]]; then
        log_error "MySQL服务启动超时"
        exit 1
    fi
    log_info "MySQL服务已就绪"

    # 等待后端应用
    log_info "等待后端应用..."
    local backend_ready=false
    for i in {1..60}; do
        if curl -s http://localhost:8080/actuator/health &> /dev/null; then
            backend_ready=true
            break
        fi
        echo -n "."
        sleep 2
    done

    if [[ "$backend_ready" == "false" ]]; then
        log_error "后端应用启动超时"
        exit 1
    fi
    log_info "后端应用已就绪"

    # 等待前端服务
    log_info "等待前端服务..."
    local frontend_ready=false
    for i in {1..30}; do
        if curl -s http://localhost/ &> /dev/null; then
            frontend_ready=true
            break
        fi
        echo -n "."
        sleep 1
    done

    if [[ "$frontend_ready" == "false" ]]; then
        log_warn "前端服务可能还在启动中"
    else
        log_info "前端服务已就绪"
    fi
}

# 停止服务
stop_services() {
    log_step "停止Docker服务..."

    if command -v docker-compose &> /dev/null; then
        docker-compose down
    else
        docker compose down
    fi

    log_info "Docker服务已停止"
}

# 重启服务
restart_services() {
    log_step "重启Docker服务..."
    stop_services
    start_services
    wait_for_services
    log_info "Docker服务重启完成"
}

# 查看日志
show_logs() {
    echo "选择要查看的服务日志:"
    echo "1) 全部服务"
    echo "2) 后端应用"
    echo "3) 前端应用"
    echo "4) MySQL数据库"
    echo "5) Redis缓存"
    read -p "请输入选择 (1-5): " choice

    case $choice in
        1)
            if command -v docker-compose &> /dev/null; then
                docker-compose logs -f
            else
                docker compose logs -f
            fi
            ;;
        2)
            docker logs -f web3-backend
            ;;
        3)
            docker logs -f web3-frontend
            ;;
        4)
            docker logs -f web3-mysql
            ;;
        5)
            docker logs -f web3-redis
            ;;
        *)
            log_error "无效选择"
            exit 1
            ;;
    esac
}

# 查看服务状态
show_status() {
    log_step "检查服务状态..."

    if command -v docker-compose &> /dev/null; then
        docker-compose ps
    else
        docker compose ps
    fi

    echo ""
    echo "服务健康状态:"
    echo "  前端: $(curl -s -o /dev/null -w "%{http_code}" http://localhost/ || echo "无法连接")"
    echo "  后端: $(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/actuator/health || echo "无法连接")"
    echo "  MySQL: $(docker exec web3-mysql mysqladmin ping -h localhost --silent && echo "正常" || echo "异常")"
    echo "  Redis: $(docker exec web3-redis redis-cli ping 2>/dev/null || echo "异常")"
}

# 显示部署信息
show_deployment_info() {
    echo ""
    echo "============================================="
    echo -e "${GREEN}       Docker部署完成！${NC}"
    echo "============================================="
    echo -e "🌐 前端访问地址: ${BLUE}http://localhost${NC}"
    echo -e "🔧 后端API地址:  ${BLUE}http://localhost:8080${NC}"
    echo -e "📊 健康检查:     ${BLUE}http://localhost:8080/actuator/health${NC}"
    echo ""
    echo -e "👤 默认账号: ${YELLOW}admin${NC}"
    echo -e "🔑 默认密码: ${YELLOW}admin123${NC}"
    echo ""
    echo "常用命令:"
    echo "  查看状态: $0 --status"
    echo "  查看日志: $0 --logs"
    echo "  重启服务: $0 --restart"
    echo "  停止服务: $0 --stop"
    echo ""
    echo "Docker命令:"
    echo "  进入后端容器: docker exec -it web3-backend bash"
    echo "  进入MySQL:    docker exec -it web3-mysql mysql -u root -p"
    echo "  查看容器状态: docker ps"
    echo "============================================="
}

# 清理资源
cleanup_resources() {
    log_step "清理Docker资源..."

    read -p "是否要清理未使用的Docker资源？(y/N): " cleanup
    if [[ $cleanup =~ ^[Yy]$ ]]; then
        docker system prune -f
        log_info "资源清理完成"
    fi
}

# 主函数
main() {
    # 检查当前目录
    if [ ! -f "docker-compose.yml" ]; then
        log_error "请在项目根目录执行此脚本"
        exit 1
    fi

    # 解析命令行参数
    MODE="default"
    REBUILD=false
    NO_CACHE=false

    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            --dev)
                MODE="dev"
                shift
                ;;
            --prod)
                MODE="prod"
                shift
                ;;
            --rebuild)
                REBUILD=true
                shift
                ;;
            --no-cache)
                NO_CACHE=true
                shift
                ;;
            --stop)
                stop_services
                exit 0
                ;;
            --restart)
                restart_services
                show_deployment_info
                exit 0
                ;;
            --logs)
                show_logs
                exit 0
                ;;
            --status)
                show_status
                exit 0
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done

    # 执行部署流程
    log_info "开始Docker部署..."

    check_docker
    check_project_files
    prepare_environment

    # 停止现有服务（如果存在）
    if docker ps | grep -q "web3-"; then
        log_info "检测到运行中的服务，先停止..."
        stop_services
    fi

    build_images
    start_services
    wait_for_services
    show_deployment_info

    # 询问是否清理资源
    cleanup_resources

    log_info "Docker部署完成！"
}

# 处理中断信号
trap 'echo -e "\n${YELLOW}[WARN]${NC} 部署被中断"; exit 1' INT TERM

# 执行主函数
main "$@"